package com.markerhub.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.lang.Result;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@CrossOrigin
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;


    Oauth oauth= new Oauth();


    @PostMapping("/login")
    public Result login(@RequestBody String oauthCode, HttpServletResponse response) throws WeiboException {


        System.out.println("oauthCode is:" + oauthCode);
        //获取AccessToken
        AccessToken token = oauth.getAccessTokenByCode(oauthCode);

        System.out.println(token);
        //获取用户信息
        Users um =new Users(token.getAccessToken());
        User user = um.showUserById(token.getUid());
        System.out.println("用户数据"+ user.toString());


        //如果记录里面没有这个用户，则添加
        com.markerhub.entity.User newUser = userService.getOne(new QueryWrapper<com.markerhub.entity.User>().eq("weibouid",token.getUid()));
        if(newUser.equals(null))
        {
            newUser =new com.markerhub.entity.User();
            newUser.setWeibouid(user.getId());
            newUser.setUsername(user.getName());
            newUser.setCreated(LocalDateTime.now());
            newUser.setStatus(0);
            newUser.setAvatar(user.getProfileImageUrl());
            userService.saveOrUpdate(newUser);

        }

//        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
//        Assert.notNull(user, "用户不存在");

//        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
//            return Result.fail("密码不正确");
//        }

        String jwt = jwtUtils.generateToken(user.getId());

//        加个登录认证头好办事
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

//      返回用户信息
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getScreenName())
                .put("avatar", user.getProfileImageURL())
                .put("gender", user.getGender())
                .map()
        );
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        System.out.println("正在注销。。。");
        SecurityUtils.getSubject().logout();
        return Result.succ(209,"注销成功",null);
    }

}
